<template>
  <div class="animate-fadeIn">
    <div class="mb-6">
      <h2 class="text-2xl font-bold cyber-text mb-2">创建设备</h2>
      <p class="text-gray-400">添加新的测试设备或服务器</p>
    </div>
    
    <div class="glass-effect rounded-xl p-6 tech-card">
      <form @submit.prevent="handleSubmit" class="space-y-6">
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-2">设备名称</label>
            <input 
              v-model="formData.name"
              type="text" 
              required
              class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all" 
              placeholder="输入设备名称"
            >
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-2">设备类型</label>
            <select 
              v-model="formData.type"
              class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all"
            >
              <option value="Linux服务器">Linux服务器</option>
              <option value="Windows服务器">Windows服务器</option>
              <option value="Docker容器">Docker容器</option>
              <option value="移动设备">移动设备</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-2">IP地址</label>
            <input 
              v-model="formData.ip"
              type="text" 
              required
              pattern="^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"
              class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all" 
              placeholder="192.168.1.100"
            >
            <p class="text-gray-500 text-xs mt-1">请输入有效的IPv4地址</p>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-2">端口</label>
            <input 
              v-model.number="formData.port"
              type="number" 
              min="1" 
              max="65535"
              required
              class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all" 
              placeholder="22"
            >
          </div>
        </div>
        
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-2">用户名</label>
            <input 
              v-model="formData.username"
              type="text" 
              required
              class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all" 
              placeholder="root"
            >
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-300 mb-2">认证方式</label>
            <select 
              v-model="formData.authMethod"
              class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all"
            >
              <option value="ssh-key">SSH密钥</option>
              <option value="password">用户名密码</option>
            </select>
          </div>
        </div>

        <!-- 根据认证方式显示不同的输入字段 -->
        <div v-if="formData.authMethod === 'password'">
          <label class="block text-sm font-medium text-gray-300 mb-2">密码</label>
          <input 
            v-model="formData.password"
            type="password" 
            class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all" 
            placeholder="输入密码"
          >
        </div>

        <div v-if="formData.authMethod === 'ssh-key'">
          <label class="block text-sm font-medium text-gray-300 mb-2">SSH私钥</label>
          <textarea 
            v-model="formData.sshKey"
            rows="6" 
            class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all font-mono text-sm" 
            placeholder="-----BEGIN RSA PRIVATE KEY-----"
          ></textarea>
        </div>

        <!-- 高级配置 -->
        <div class="border-t border-gray-700 pt-6">
          <h3 class="text-lg font-semibold text-gray-300 mb-4">高级配置</h3>
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">连接超时（秒）</label>
              <input 
                v-model.number="formData.timeout"
                type="number" 
                min="1" 
                max="300"
                class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all" 
                placeholder="30"
              >
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-300 mb-2">最大并发连接数</label>
              <input 
                v-model.number="formData.maxConnections"
                type="number" 
                min="1" 
                max="100"
                class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all" 
                placeholder="10"
              >
            </div>
          </div>
          
          <div class="mt-4">
            <label class="flex items-center space-x-3">
              <input 
                v-model="formData.autoConnect"
                type="checkbox" 
                class="text-tech-blue focus:ring-tech-blue"
              >
              <span class="text-gray-300">启动时自动连接</span>
            </label>
          </div>
        </div>
        
        <div>
          <label class="block text-sm font-medium text-gray-300 mb-2">设备描述</label>
          <textarea 
            v-model="formData.description"
            rows="3" 
            class="w-full px-4 py-3 border border-gray-600 rounded-lg bg-gray-800/50 text-white focus:outline-none focus:ring-2 focus:ring-tech-blue neon-border transition-all" 
            placeholder="描述设备用途和配置"
          ></textarea>
        </div>
        
        <div class="flex justify-end space-x-4">
          <router-link 
            to="/device/list"
            class="px-6 py-3 border border-gray-600 text-gray-300 rounded-lg hover:bg-gray-700 transition-colors"
          >
            取消
          </router-link>
          <button 
            type="button"
            @click="testConnection"
            :disabled="isTestingConnection"
            class="px-6 py-3 border border-tech-blue text-tech-blue rounded-lg hover:bg-tech-blue hover:text-white transition-colors disabled:opacity-50"
          >
            <i class="fas fa-link mr-2"></i>
            {{ isTestingConnection ? '测试中...' : '测试连接' }}
          </button>
          <button 
            type="submit" 
            :disabled="isSubmitting"
            class="cyber-button px-6 py-3 text-white rounded-lg hover-glow transition-all duration-200 disabled:opacity-50"
          >
            <i class="fas fa-save mr-2"></i>
            {{ isSubmitting ? '添加中...' : '添加设备' }}
          </button>
        </div>
      </form>
    </div>

    <!-- 连接测试结果模态框 -->
    <ConnectionTestModal 
      v-if="showTestResult"
      :result="testResult"
      @close="showTestResult = false"
    />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import ConnectionTestModal from '@/components/device/ConnectionTestModal.vue'

const router = useRouter()

const formData = reactive({
  name: '',
  type: 'Linux服务器',
  ip: '',
  port: 22,
  username: 'root',
  authMethod: 'ssh-key',
  password: '',
  sshKey: '',
  timeout: 30,
  maxConnections: 10,
  autoConnect: true,
  description: ''
})

const isSubmitting = ref(false)
const isTestingConnection = ref(false)
const showTestResult = ref(false)
const testResult = ref<{ success: boolean; message: string; details?: any }>({
  success: false,
  message: ''
})

const testConnection = async () => {
  isTestingConnection.value = true
  
  try {
    // 模拟连接测试
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    // 模拟测试结果
    const success = Math.random() > 0.3 // 70% 成功率
    
    testResult.value = {
      success,
      message: success ? '连接测试成功！设备响应正常。' : '连接测试失败。请检查网络设置和认证信息。',
      details: success ? {
        latency: '2ms',
        os: 'Ubuntu 20.04 LTS',
        cpuCores: 8,
        memory: '16GB'
      } : {
        error: 'Connection timeout',
        code: 'ETIMEDOUT'
      }
    }
    
    showTestResult.value = true
  } catch (error) {
    console.error('连接测试失败:', error)
  } finally {
    isTestingConnection.value = false
  }
}

const handleSubmit = async () => {
  isSubmitting.value = true
  
  try {
    // 模拟保存设备
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    console.log('添加设备:', formData)
    alert('设备添加成功！')
    router.push('/device/list')
  } catch (error) {
    console.error('添加设备失败:', error)
    alert('添加设备失败，请重试。')
  } finally {
    isSubmitting.value = false
  }
}
</script>

